package c.x.jy.wexin.config;

import java.util.UUID;

import c.x.jy.service.redis.Cache;
import c.x.jy.service.service.OrderAwnserService;
import c.x.jy.service.utils.mqtt.OutPaperBackMsg;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import c.x.jy.common.mqtt.ReadConfig;
import c.x.jy.service.utils.mqtt.PushCallback;
import lombok.extern.slf4j.Slf4j;
//@EnableConfigurationProperties({ PushCallback.class})
@Slf4j
@Configuration
public class MqttConfig {

	@Bean
	public MqttClient MqttClient(PushCallback pushCallback) {
			String clinentId = UUID.randomUUID().toString().replaceAll("-", "").trim();
			log.info(ReadConfig.getMqttHost() + "/" + ReadConfig.getMqttServerClient());
			MqttClient client = null;
			try {
				client = new MqttClient(ReadConfig.getMqttHost(), clinentId, new MemoryPersistence());
			//ReadConfig.getMqttHost()
			MqttConnectOptions connOpts = new MqttConnectOptions();
			// MQTT 连接选项
			// connOpts = new MqttConnectOptions();
			connOpts.setUserName(ReadConfig.getMqttClientrUser());
			connOpts.setPassword(ReadConfig.getMqttClientrPassword().toCharArray());
			// 设置超时时间 单位为秒
			connOpts.setConnectionTimeout(10);
			// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
			connOpts.setKeepAliveInterval(20);
			// 保留会话
			connOpts.setCleanSession(true);
			// 设置重连机制
			connOpts.setAutomaticReconnect(true);
			// 建立连接
			log.info("Connecting to Host: " + ReadConfig.getMqttHost());
			client.connect(connOpts);
			// 设置回调
			client.setCallback(pushCallback);
		 	client.subscribe(ReadConfig.getMqttServerClient(), 1);
			} catch (MqttException e) {
				e.printStackTrace();
			}
		  pushCallback.init(client);
			return client;
 
 
	}
	@Bean
	public	PushCallback PushCallback(OutPaperBackMsg outPaperBackMsg){
    return  new PushCallback(outPaperBackMsg);
	}
	@Bean
	public OutPaperBackMsg outPaperBackMsg(Cache redisUtils ){
		return  new OutPaperBackMsg(redisUtils);
	};



}
